package com.tanhua.app.Service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.api.*;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.interceptor.UserThreadLocal;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.pojo.Question;
import com.tanhua.model.pojo.User;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import org.apache.commons.collections.map.HashedMap;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private UserLocationApi userLocationApi;

    @Autowired
    private VisitorsApi visitorsApi;


    @Autowired
    private MessagesService messagesService;
    //查询今日佳人数据
    public TodayBest todayBest() {
        //1 获取用户id
        Long userId = UserThreadLocal.getid();
        //2 调用API查询
        RecommendUser recommendUser = recommendUserApi.findWithMaxScore(userId);
        //3 将RecommendUser转化为TodayBest对象
        UserInfo userInfo = userInfoApi.selectById(recommendUser.getUserId());
        TodayBest vo = TodayBest.init(userInfo, recommendUser);
        //4 返回
        return vo;
    }

    public PageResult<TodayBest> recommendation(RecommendUserDto recommendUserDto) {
        Long MyUserId = UserThreadLocal.getid();
        List<RecommendUser> recommendUserList = recommendUserApi.findRecommendUser(MyUserId);
        if (recommendUserList == null || recommendUserList.size() == 0) {
            return new PageResult<>(recommendUserDto.getPage(), recommendUserDto.getPagesize(), 0, null);
        }
        Page<UserInfo> pages = userInfoApi.findUsersByIds(recommendUserList, recommendUserDto);
        List<UserInfo> userInfoList = pages.getRecords();
        Map<Long, RecommendUser> map = recommendUserList.stream().collect(Collectors.toMap(RecommendUser::getUserId, Function.identity()));
        ArrayList<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            RecommendUser recommendUser = map.get(userInfo.getId());
            TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
            todayBests.add(todayBest);
        }
        return new PageResult<TodayBest>(recommendUserDto.getPage(), recommendUserDto.getPagesize(), (int) pages.getTotal(), todayBests);

    }

    //根据佳人id查询佳人详细信息
    public TodayBest todayBestByid(Long id) {
//        1.根据用户id查询,用户详情
        UserInfo userInfo = userInfoApi.selectById(id);
//        2.根据操作人id和查看的用户id,查询两者的推荐数据
        RecommendUser recommendUser = recommendUserApi.findRecommendById(id, UserThreadLocal.getid());

//        构造访客数据,调用API保存
        Visitors visitors = new Visitors();

        visitors.setVisitorUserId(UserThreadLocal.getid());
        visitors.setUserId(id);
        visitors.setFrom("首页");
        visitors.setDate(System.currentTimeMillis());
        visitors.setVisitDate(new SimpleDateFormat("yyyMMdd").format(new Date()));
        visitorsApi.save(visitors);



        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
        return todayBest;
    }

    //根据用户id查询陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findById(userId);
        return question == null ? "你工资多少" : question.getTxt();
    }

    //回复陌生人信息
    public void replyQuestions(Long userId, String reply) {
        HashedMap map = new HashedMap();
        Long getid = UserThreadLocal.getid();
        UserInfo userInfo = userInfoApi.selectById(getid);
        map.put("userId", getid);
        map.put("huanXinId", Constants.HX_USER_PREFIX + getid);
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", strangerQuestions(userId));
        map.put("reply", reply);
        String jsonString = JSON.toJSONString(map);
        Boolean aBoolean = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + userId, jsonString);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }

          /*  "userId": 106,
                "huanXinId": "hx106",
                "nickname": "黑马小妹",
                "strangerQuestion": "你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
                "reply": "我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"*/

    }

    /**
     * /探花左滑右滑（推荐佳人）
     *
     * @return
     */
    @Value("${tanhua.default.recommend.users}")
    private List<Long> userIds;

    public List<TodayBest> queryCardsList() {
        List<RecommendUser> recommendUserList = recommendUserApi.findRecommendUserById(UserThreadLocal.getid());
        if (CollUtil.isEmpty(recommendUserList)) {
            recommendUserList = new ArrayList<>();
            for (Long userId : userIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setToUserId(UserThreadLocal.getid());
                recommendUser.setUserId(userId);
                recommendUser.setScore(RandomUtil.randomDouble(60, 90));
                recommendUserList.add(recommendUser);
            }
        }
        List<Long> users = recommendUserList.stream().map(RecommendUser::getUserId).collect(Collectors.toList());
        List<UserInfo> userInfoList = userInfoApi.findUserinfoByIds(users);
        List<TodayBest> todayBests = new ArrayList<>();
        Map<Long, UserInfo> map = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
        for (RecommendUser recommendUser : recommendUserList) {
            Long userId = recommendUser.getUserId();
            UserInfo userInfo = map.get(userId);
            if (userInfo != null) {
                TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
                todayBests.add(todayBest);
            }

        }
        return todayBests;

    }

    //左滑右滑喜欢
    public void love(Long id) {
        //保存喜欢好友
        boolean a = userLikeApi.save(UserThreadLocal.getid(), id, true);
        if (!a) {
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY + UserThreadLocal.getid(), id.toString());
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY + UserThreadLocal.getid(), id.toString());

      UserLike userLike= userLikeApi.findById(id,UserThreadLocal.getid(),true);
      if (userLike != null) {
         messagesService.contacts(id);
      }

    }

    public void notLikeUser(Long id) {

        //保存不喜欢好友
        boolean a = userLikeApi.save(UserThreadLocal.getid(), id, false);
        if (!a) {
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY + UserThreadLocal.getid(), id.toString());
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY + UserThreadLocal.getid(), id.toString());

        UserLike userLike= userLikeApi.findById(id,UserThreadLocal.getid(),false);
        if (userLike != null) {
            messagesService.deleteContacts(id);
        }

    }

    //搜附近
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //1、调用API查询附近的用户（返回的是附近的人的所有用户id，包含当前用户的id）
        List<Long> userIds = userLocationApi.queryNearUser(UserThreadLocal.getid(), Double.valueOf(distance));
        //2、判断集合是否为空
        if (CollUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        //3、调用UserInfoApi根据用户id查询用户详情
        List<UserInfo> userInfoList = userInfoApi.findByUserIds(userIds,gender);
        //4、构造返回值。
        List<NearUserVo> vos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            if (UserThreadLocal.getid().longValue() == userInfo.getId().longValue()) {
                continue;
            }
            NearUserVo vo = NearUserVo.init(userInfo);
            vos.add(vo);
        }

        return vos;
    }
}